package edu.nju.desserthouse.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nju.edu.desserthouse.model.Goods;
import nju.edu.desserthouse.model.Sale;

import edu.nju.desserthouse.action.business.BestSellerInfoBean;
import edu.nju.desserthouse.dao.GoodsDao;
import edu.nju.desserthouse.dao.SaleDao;

/**
 * Servlet implementation class BestSellerServlet
 */
@WebServlet("/bestseller.manager")
public class BestSellerServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	
	@EJB
	SaleDao saleDao;
	@EJB
	GoodsDao goodsDao;
	
    public BestSellerServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute (request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute (request, response);
	}

	public void execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		ArrayList<Sale> saleList = saleDao.getSaleList();
		BestSellerInfoBean bestSellerInfo = new BestSellerInfoBean();
		bestSellerInfo.setGoods(goodsDao.getGoodsList("belong", "0"));
		bestSellerInfo.initList();
		for(int i = 0; i < saleList.size(); i++){
			bestSellerInfo.addToSale((saleList.get(i).getGoods() - 1)%30);
			System.out.println(saleList.get(i).getGoods()%30);
		}
		
		int temp = 0;
		Goods tempGoods = null;
		int length = bestSellerInfo.getGoods().size();
		for(int i = 0; i < length; i++){
			for(int j = i + 1; j < length; j++){
				if(bestSellerInfo.getSale(i) < bestSellerInfo.getSale(j)){
					temp = bestSellerInfo.getSale(i);
					bestSellerInfo.setSale(i, bestSellerInfo.getSale(j));
					bestSellerInfo.setSale(j, temp);
					tempGoods = bestSellerInfo.getGoods().get(i);
					bestSellerInfo.getGoods().set(i, bestSellerInfo.getGoods().get(j));
					bestSellerInfo.getGoods().set(j, tempGoods);
				}
			}
		}
		
		req.getSession().setAttribute("bestSellerInfo", bestSellerInfo);
		
		resp.sendRedirect("/desserthouseWEB/manager/bestseller.jsp");
	}
}
